package com.smile.cloud.redisConfig.distributedLock.redisson;



import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * redisson 分布式锁实现
 */
@Component
public class RedissonLocker implements DistributedLocker {

    private final static String LOCKER_PREFIX = "redisson:lock:";

    @Autowired
    private RedissonClient redissonClient;

    @Override
    public <T> T lock(String resourceName, AquiredLockWorker<T> worker) throws InterruptedException, UnableToAquireLockException, Exception {
        return lock(resourceName, worker, TIME_OUT, TimeUnit.SECONDS);
    }

    @Override
    public <T> T lock(String resourceName, AquiredLockWorker<T> worker, long lockTime, TimeUnit timeUnit) throws UnableToAquireLockException, Exception {
        RLock lock = redissonClient.getLock(LOCKER_PREFIX + resourceName);
        boolean success = lock.tryLock(100, lockTime, timeUnit);
        if (success) {
            try {
                return worker.invokeAfterLockAquire();
            } finally {
                lock.unlock();
            }
        }
        throw new UnableToAquireLockException();
    }
}